package com.quectel.mobile.controller.partybuilding;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.constant.core.partybuilding.PartySurveyConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.core.module.partybuildingsurvey.dto.*;
import com.quectel.core.module.partybuildingsurvey.service.*;
import com.quectel.core.module.partybuildingtask.dto.PartyBuildingPlanTaskDto;
import com.quectel.mobile.controller.BaseController;
import com.quectel.mobile.util.SessionHolder;
import com.quectel.mobile.vo.partybuilding.PartySurveySubmitReq;
import com.quectel.util.common.*;
import com.quectel.util.redis.RedisUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 在这里编写说明
 *
 * @author: bob
 * @email: bob.yu@quectel.com
 * @date: 2023-06-13 13:58:00
 */
@RestController
@RequestMapping("partySurvey")
@Tag(name = "PartySurveyController", description = "智慧党建-民意调查/民主投票相关api")
public class PartySurveyController extends BaseController {

    @DubboReference
    private PartyOrganizationService partyOrganizationService;
    @DubboReference
    private PartyPersonService partyPersonService;
    @DubboReference
    private PartySurveyService partySurveyService;
    @DubboReference
    private PartySurveyPersonBindingService partySurveyPersonBindingService;
    @DubboReference
    private PartySurveyPersonRecordService partySurveyPersonRecordService;
    @DubboReference
    private PartySurveyPersonAnswerService partySurveyPersonAnswerService;
    @DubboReference
    private PartySurveyQuestionService partySurveyQuestionService;
    private static final Byte ALL = 1;
    private static final Byte WAIT_TO_PARTICIPATE = 2;
    private static final Byte HAVE_PARTICIPATED = 3;
    private static final String EXEC_STATUSES = "execStatuses";

    private static final String PARTY_SURVEY_PERSON_RECORD_LOCK_KEY = "PARTY_SURVEY_PERSON_RECORD_LOCK_KEY:%d:%d";


    /**
     * 全部：显示全部状态；待参加：参加状态是0；已参加：参加状态是1；
     *
     * @param queryRange
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @Operation(summary = "党建调查问卷分页查询列表")
    public Response<Page<PartySurveyPersonBindingDto>> list(
            @Parameter(description = "查询范围1全部2待参加3已参加") @RequestParam Byte queryRange,
            @Parameter(description = "1民意调查2民主投票") @RequestParam Byte category,
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        SessionHolder.checkMobileUser();
        SessionHolder.checkPartyPerson();
        PartyPersonDto partyPerson = Objects.requireNonNull(SessionHolder.getLoginMobileUserSession()).getPartyPerson();
        Map<String, Object> params = new HashMap<>();
        Request request = Request.configParams(params);

        request.getParams().put(LambdaUtil.getFieldName(PartySurveyPersonBindingDto::getPersonId), partyPerson.getId());
        request.getParams().put(LambdaUtil.getFieldName(PartySurveyPersonBindingDto::getCategory), category);

        if (queryRange.equals(WAIT_TO_PARTICIPATE)) {
            request.getParams().put(LambdaUtil.getFieldName(PartySurveyPersonBindingDto::getParticipateStatus), SystemConstants.NO);
            //待参加的必须在开放时间范围内
            request.getParams().put(PartySurveyConstants.PARTY_SURVEY_QUERY_TIME, DateUtils.format(new Date(), DateUtils.FormatType.COMMON));
        } else if (queryRange.equals(HAVE_PARTICIPATED)) {
            request.getParams().put(LambdaUtil.getFieldName(PartySurveyPersonBindingDto::getParticipateStatus), SystemConstants.YES);
        }

        request.getParams().put(PartySurveyConstants.PARTY_SURVEY_STATUSES, Arrays.asList(PartySurveyConstants.MarkStatus.PUBLISHED.getStatus(), PartySurveyConstants.MarkStatus.CANCELED.getStatus()));

        int totalCount = partySurveyPersonBindingService.querySurveyTotal(request.getParams());
        List<PartySurveyPersonBindingDto> list = null;
        if (totalCount > 0) {
            list = partySurveyPersonBindingService.querySurveyList(params);
            list.forEach(
                    partySurveyPersonBindingDto -> {
                        PartySurveyDto partySurveyDto = partySurveyService.selectCacheById(partySurveyPersonBindingDto.getPartySurveyId());
                        if (partySurveyDto != null) {
                            Integer totalRecordCount = getTotalRecordCount(partySurveyDto.getId(), partySurveyPersonBindingDto.getPersonId());
                            Integer todayRecordCount = getTodayRecordCount(partySurveyDto.getId(), partySurveyPersonBindingDto.getPersonId());
                            if (totalRecordCount < partySurveyDto.getPersonLimit() && todayRecordCount < partySurveyDto.getDayLimit()) {
                                partySurveyPersonBindingDto.setAnswerFlag(SystemConstants.YES);
                            } else {
                                partySurveyPersonBindingDto.setAnswerFlag(SystemConstants.NO);
                            }
                        }
                    }
            );

        } else {
            list = new ArrayList<>();
        }
        Page<PartySurveyPersonBindingDto> page = new Page<>(request.getPageNo(), request.getPageSize(), totalCount, list);
        return Response.<Page<PartySurveyPersonBindingDto>>ok().wrap(page);
    }

    /**
     * 查看详情
     *
     * @param id
     * @return
     */
    @GetMapping("infoSurvey/{id}")
    @Operation(summary = "查询问卷详情")
    public Response<PartySurveyDto> infoSurvey(@PathVariable("id") Long id) {
        SessionHolder.checkMobileUser();
        SessionHolder.checkPartyPerson();

        PartyPersonDto partyPerson = Objects.requireNonNull(SessionHolder.getLoginMobileUserSession()).getPartyPerson();
        Map<String, Object> params = new HashMap<>();
        Request request = Request.configParams(params);

        request.getParams().put(LambdaUtil.getFieldName(PartySurveyDto::getId), id);
        request.getParams().put(LambdaUtil.getFieldName(PartySurveyDto::getTenantId), partyPerson.getTenantId());

        if (partySurveyService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartySurveyDto partySurveyDto = partySurveyService.selectCacheById(id);
        partySurveyDto.setTotalCount(getTotalRecordCount(partySurveyDto.getId(), partyPerson.getId()));
        partySurveyDto.setDayCount(getTodayRecordCount(partySurveyDto.getId(), partyPerson.getId()));

        return Response.<PartySurveyDto>ok().wrap(partySurveyDto);
    }

    /**
     * 查看答题详情
     *
     * @param id
     * @return
     */
    @GetMapping("infoResult/{id}")
    @Operation(summary = "查询问卷详情")
    public Response<PartySurveyPersonRecordDto> infoResult(@PathVariable("id") Long id) {
        SessionHolder.checkMobileUser();
        SessionHolder.checkPartyPerson();

        PartyPersonDto partyPerson = Objects.requireNonNull(SessionHolder.getLoginMobileUserSession()).getPartyPerson();
        Map<String, Object> params = new HashMap<>();
        Request request = Request.configParams(params);

        request.getParams().put(LambdaUtil.getFieldName(PartySurveyDto::getId), id);
        request.getParams().put(LambdaUtil.getFieldName(PartySurveyDto::getTenantId), partyPerson.getTenantId());

        if (partySurveyService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartySurveyDto partySurveyDto = partySurveyService.selectCacheById(id);
        partySurveyDto.setTotalCount(getTotalRecordCount(partySurveyDto.getId(), partyPerson.getId()));
        partySurveyDto.setDayCount(getTodayRecordCount(partySurveyDto.getId(), partyPerson.getId()));


        //查询是否参加
        PartySurveyPersonBindingDto partySurveyPersonBindingDto = partySurveyPersonBindingService.selectBySurveyIdAndPersonId(partySurveyDto.getId(), partyPerson.getId());
        if (partySurveyPersonBindingDto == null || SystemConstants.NO.equals(partySurveyPersonBindingDto.getParticipateStatus())) {
            return Response.error("未查询到记录");
        }

        //查询最新一次答题记录
        PartySurveyPersonRecordDto partySurveyPersonRecordDto = partySurveyPersonRecordService.selectLastBySurveyIdAndPersonId(partySurveyDto.getId(), partyPerson.getId());
        if (partySurveyPersonRecordDto == null) {
            return Response.error("未查询到记录");
        }
        List<PartySurveyPersonAnswerDto> partySurveyPersonAnswerDtos = partySurveyPersonAnswerService.selectByRecordId(partySurveyPersonRecordDto.getId());
        Map<Long, PartySurveyPersonAnswerDto> collect = partySurveyPersonAnswerDtos.stream().collect(Collectors.toMap(PartySurveyPersonAnswerDto::getQuestionId, Function.identity(), (key1, key2) -> key2));

        List<PartySurveyQuestionDto> partySurveyQuestionDtos = new ArrayList<>(partySurveyDto.getBindQuestion().size());
        //将题目和答案组装
        partySurveyDto.getBindQuestion().forEach(
                partySurveyQuestionDto -> {
                    PartySurveyPersonAnswerDto partySurveyPersonAnswerDto = collect.get(partySurveyQuestionDto.getId());
                    partySurveyQuestionDto.setPartySurveyPersonAnswer(partySurveyPersonAnswerDto);

                    //允许查询结果
                    if (SystemConstants.YES.equals(partySurveyDto.getKnowResult())) {
                        partySurveyQuestionDto = partySurveyQuestionService.questionCount(partySurveyQuestionDto);
                    }
                    partySurveyQuestionDtos.add(partySurveyQuestionDto);
                }
        );
        partySurveyDto.setBindQuestion(partySurveyQuestionDtos);
        partySurveyPersonRecordDto.setPartySurvey(partySurveyDto);

        return Response.<PartySurveyPersonRecordDto>ok().wrap(partySurveyPersonRecordDto);
    }


    /**
     * 提交答题记录
     *
     * @param req
     * @return
     */
    @PostMapping("submit")
    @Operation(summary = "提交答题记录")
    public Response submit(@RequestBody @Validated PartySurveySubmitReq req) {
        SessionHolder.checkMobileUser();
        SessionHolder.checkPartyPerson();

        PartyPersonDto partyPerson = Objects.requireNonNull(SessionHolder.getLoginMobileUserSession()).getPartyPerson();
        //查询
        PartySurveyDto partySurveyDto = partySurveyService.selectCacheById(req.getPartySurveyId());
        if (partySurveyDto == null) {
            return Response.error("未查询到问卷信息，请联系管理员");
        }
        PartySurveyPersonBindingDto partySurveyPersonBindingDto = partySurveyPersonBindingService.selectBySurveyIdAndPersonId(partySurveyDto.getId(), partyPerson.getId());
        if (partySurveyPersonBindingDto == null) {
            return Response.error("没有答题权限");
        }

        //是否允许匿名提交 如果不允许匿名提交
        if (SystemConstants.NO.equals(partySurveyDto.getAllowAnonymous()) && SystemConstants.YES.equals(req.getAnonymous())) {
            return Response.error("不允许匿名提交");
        }

        if (PartySurveyConstants.Category.DEMOCRATIC_VOTING.getCategory().equals(partySurveyDto.getCategory())) {
            //如果超过总次数
            if (partySurveyDto.getPersonLimit() != null && getTotalRecordCount(req.getPartySurveyId(), partyPerson.getId()) >= partySurveyDto.getPersonLimit()) {

                return Response.error("超过投票最大次数");
            }
            if (partySurveyDto.getDayLimit() != null && getTodayRecordCount(req.getPartySurveyId(), partyPerson.getId()) >= partySurveyDto.getDayLimit()) {
                return Response.error("超过每日投票最大次数");
            }
        }

        //题目校验
        List<PartySurveyQuestionDto> bindQuestion = partySurveyDto.getBindQuestion();
        if (CollectionUtils.isEmpty(bindQuestion)) {
            return Response.error("问卷内容错误，请联系管理员");
        }
        Map<Long, Object> answers = req.getAnswers();
        List<PartySurveyPersonAnswerDto> partySurveyPersonAnswerDtos = new ArrayList<>(bindQuestion.size());
        PartySurveyPersonRecordDto partySurveyPersonRecordDto = new PartySurveyPersonRecordDto();
        for (PartySurveyQuestionDto partySurveyQuestionDto : bindQuestion) {
            if (SystemConstants.YES.equals(partySurveyQuestionDto.getNecessary()) && answers.get(partySurveyQuestionDto.getId()) == null) {
                //如果题目是必填的 但是没有对应的答案
                return Response.error("第" + partySurveyQuestionDto.getSort() + "题必填题目没有回答，请回答之后再次提交");
            }
            //如果是多选 则判断选项是否符合要求
            if (PartySurveyConstants.QuestionType.MULTIPLE_CHOICE.getType().equals(partySurveyQuestionDto.getType()) ||
                    PartySurveyConstants.QuestionType.PIC_MULTIPLE_CHOICE.getType().equals(partySurveyQuestionDto.getType())
            ) {
                PartySurveyQuestionDto.MultipleConfig multipleConfig = partySurveyQuestionDto.getMultipleConfig();
                List<String> selectedOptions = (List<String>) answers.get(partySurveyQuestionDto.getId());
                if (CollectionUtils.isEmpty(selectedOptions)) {
                    return Response.error("第" + partySurveyQuestionDto.getSort() + "题至少选择一个选项");
                }
                if (multipleConfig != null && multipleConfig.getMaxSelected() != null && multipleConfig.getMaxSelected() < selectedOptions.size()) {
                    return Response.error("第" + partySurveyQuestionDto.getSort() + "题超过最大选择数量");
                }

            }
            PartySurveyPersonAnswerDto partySurveyPersonAnswerDto = new PartySurveyPersonAnswerDto();
            partySurveyPersonAnswerDto.setQuestionId(partySurveyQuestionDto.getId());
            partySurveyPersonAnswerDto.setPartySurveyId(partySurveyQuestionDto.getPartySurveyId());
            partySurveyPersonAnswerDto.setContent(JacksonUtils.toJsonString(answers.get(partySurveyQuestionDto.getId())));
            partySurveyPersonAnswerDtos.add(partySurveyPersonAnswerDto);

        }

        Lock spinLock = RedisUtils.getSpinLock(String.format(PARTY_SURVEY_PERSON_RECORD_LOCK_KEY, req.getPartySurveyId(), partyPerson.getId()));
        spinLock.lock();
        try {

            partySurveyPersonRecordDto.setPartySurveyId(partySurveyDto.getId());
            partySurveyPersonRecordDto.setPersonId(partyPerson.getId());
            partySurveyPersonRecordDto.setAnonymous(req.getAnonymous());
            partySurveyPersonRecordDto.setCreateTime(new Date());
            partySurveyPersonRecordDto.setPersonAnswerList(partySurveyPersonAnswerDtos);

            partySurveyPersonRecordService.submit(partySurveyPersonRecordDto);

            invalidRecordCache(partySurveyDto.getId(), partyPerson.getId());

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            spinLock.unlock();
        }

        return Response.<PartyBuildingPlanTaskDto>ok();
    }

    private static final String PARTY_SURVEY_PERSON_TOTAL_RECORD_KEY = "PARTY_SURVEY_PERSON_TOTAL_RECORD:%d:%d";
    private static final String PARTY_SURVEY_PERSON_TODAY_RECORD_KEY = "PARTY_SURVEY_PERSON_TODAY_RECORD_KEY:%s:%d:%d";
    private static final String QUERY_DATE_START = "queryDateStart";
    private static final String QUERY_DATE_END = "queryDateEnd";

    private Integer getTotalRecordCount(Long surveyId, Long personId) {
        String s = RedisUtils.get(String.format(PARTY_SURVEY_PERSON_TOTAL_RECORD_KEY, surveyId, personId));
        if (StringUtils.isBlank(s)) {
            Map<String, Object> params = new HashMap<>();
            params.put(LambdaUtil.getFieldName(PartySurveyPersonRecordDto::getPartySurveyId), surveyId);
            params.put(LambdaUtil.getFieldName(PartySurveyPersonRecordDto::getPersonId), personId);

            int i = partySurveyPersonRecordService.queryTotal(params);
            RedisUtils.set(String.format(PARTY_SURVEY_PERSON_TOTAL_RECORD_KEY, surveyId, personId), String.valueOf(i), 5, TimeUnit.MINUTES);
            return i;
        } else {
            return Integer.valueOf(s);
        }
    }

    private Integer getTodayRecordCount(Long surveyId, Long personId) {
        Date now = new Date();
        String date = DateUtils.format(now, DateUtils.FormatType.SIMPLE);
        String dateStart = DateUtils.format(DateUtil.beginOfDay(now), DateUtils.FormatType.COMMON);
        String dateEnd = DateUtils.format(DateUtil.endOfDay(now), DateUtils.FormatType.COMMON);

        String s = RedisUtils.get(String.format(PARTY_SURVEY_PERSON_TODAY_RECORD_KEY, date, surveyId, personId));
        if (StringUtils.isBlank(s)) {
            Map<String, Object> params = new HashMap<>();
            params.put(LambdaUtil.getFieldName(PartySurveyPersonRecordDto::getPartySurveyId), surveyId);
            params.put(LambdaUtil.getFieldName(PartySurveyPersonRecordDto::getPersonId), personId);
            params.put(QUERY_DATE_START, dateStart);
            params.put(QUERY_DATE_END, dateEnd);
            int i = partySurveyPersonRecordService.queryTotal(params);
            RedisUtils.set(String.format(PARTY_SURVEY_PERSON_TODAY_RECORD_KEY, date, surveyId, personId), String.valueOf(i), 5, TimeUnit.MINUTES);
            return i;
        } else {
            return Integer.valueOf(s);
        }
    }

    private void invalidRecordCache(Long surveyId, Long personId) {
        RedisUtils.del(String.format(PARTY_SURVEY_PERSON_TOTAL_RECORD_KEY, surveyId, personId));
        RedisUtils.del(String.format(PARTY_SURVEY_PERSON_TODAY_RECORD_KEY, DateUtils.format(new Date(), DateUtils.FormatType.SIMPLE), surveyId, personId));
    }

//    @GetMapping("getTodayRecordCount/{surveyId}/{personId}")
//    @Operation(summary = "查询问卷详情")
//    public Response<Integer> infoResult(@PathVariable("surveyId") Long surveyId,@PathVariable("personId") Long personId) {
//
//        invalidRecordCache(surveyId,personId);
//
//        return Response.<Integer>ok().wrap(0);
//    }

}
